/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package databaseapp;

import java.sql.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import net.proteanit.sql.DbUtils;
//import java.math.RoundingMode;

/**
 *
 * @author ADMIN
 */
public class MainForm extends javax.swing.JFrame {

    Connection conn = null;
    PreparedStatement statement = null;
    ResultSet rs = null;

    public MainForm() throws SQLException {
        initComponents();
    }

    private void UpdateJTable() {
        String sql = "Select * from sinhvien";
        try {
            statement = conn.prepareStatement(sql);
            rs = statement.executeQuery();
            tblSinhiven.setModel(DbUtils.resultSetToTableModel(rs));
        } catch (Exception ex) {
            JOptionPane.showMessageDialog(null, ex);
        }
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        tfHoten = new javax.swing.JTextField();
        tfDiachi = new javax.swing.JTextField();
        btnLuu = new javax.swing.JButton();
        lblNhapThongtin = new javax.swing.JLabel();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        tblSinhiven = new javax.swing.JTable();
        tfDiemly = new javax.swing.JTextField();
        tfDiemtoan = new javax.swing.JTextField();
        tfDiemhoa = new javax.swing.JTextField();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        jLabel6 = new javax.swing.JLabel();
        btnXoa = new javax.swing.JButton();
        btnCapnhat = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Thông tin Sinh viên");
        setForeground(java.awt.Color.lightGray);
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowOpened(java.awt.event.WindowEvent evt) {
                formWindowOpened(evt);
            }
        });

        btnLuu.setIcon(new javax.swing.ImageIcon(getClass().getResource("/databaseapp/save.png"))); // NOI18N
        btnLuu.setText("Nhập Mới");
        btnLuu.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnLuuActionPerformed(evt);
            }
        });

        lblNhapThongtin.setFont(new java.awt.Font("Times New Roman", 1, 14)); // NOI18N
        lblNhapThongtin.setForeground(new java.awt.Color(255, 0, 0));
        lblNhapThongtin.setText("Nhập Thông tin Sinh viên");

        jLabel1.setText("Họ Tên");

        jLabel2.setText("Địa chỉ");

        tblSinhiven.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "ID", "Họ và Tên", "Địa Chĩ", "Điểm Toán", "Điểm Lý", "Điểm Hóa", "Điểm TB"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.Integer.class, java.lang.String.class, java.lang.String.class, java.lang.Integer.class, java.lang.Integer.class, java.lang.Integer.class, java.lang.Double.class
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }
        });
        tblSinhiven.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                tblSinhivenMouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(tblSinhiven);

        jLabel3.setText("Điểm");

        jLabel4.setText("Toán");

        jLabel5.setText("Lý");

        jLabel6.setText("Hóa");

        btnXoa.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icon/delete.png"))); // NOI18N
        btnXoa.setText("Xóa");
        btnXoa.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnXoaActionPerformed(evt);
            }
        });

        btnCapnhat.setIcon(new javax.swing.ImageIcon(getClass().getResource("/databaseapp/update.png"))); // NOI18N
        btnCapnhat.setText("Cập nhật");
        btnCapnhat.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnCapnhatActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel3)
                        .addGap(26, 26, 26)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jLabel4)
                                .addGap(50, 50, 50)
                                .addComponent(jLabel5)
                                .addGap(71, 71, 71)
                                .addComponent(jLabel6, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                                .addGroup(layout.createSequentialGroup()
                                    .addComponent(btnLuu)
                                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                    .addComponent(btnCapnhat, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                    .addComponent(btnXoa)
                                    .addContainerGap(243, Short.MAX_VALUE))
                                .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                                    .addComponent(tfDiemtoan, javax.swing.GroupLayout.PREFERRED_SIZE, 64, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                    .addComponent(tfDiemly, javax.swing.GroupLayout.PREFERRED_SIZE, 64, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addGap(18, 18, 18)
                                    .addComponent(tfDiemhoa, javax.swing.GroupLayout.PREFERRED_SIZE, 64, javax.swing.GroupLayout.PREFERRED_SIZE)))))
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 523, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                .addComponent(lblNhapThongtin, javax.swing.GroupLayout.PREFERRED_SIZE, 327, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                                    .addComponent(jLabel1)
                                    .addGap(16, 16, 16)
                                    .addComponent(tfHoten, javax.swing.GroupLayout.PREFERRED_SIZE, 174, javax.swing.GroupLayout.PREFERRED_SIZE))
                                .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                                    .addComponent(jLabel2)
                                    .addGap(18, 18, 18)
                                    .addComponent(tfDiachi, javax.swing.GroupLayout.PREFERRED_SIZE, 174, javax.swing.GroupLayout.PREFERRED_SIZE))))
                        .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(lblNhapThongtin, javax.swing.GroupLayout.PREFERRED_SIZE, 27, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(tfHoten, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel1))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(tfDiachi, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel2))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel4)
                    .addComponent(jLabel5)
                    .addComponent(jLabel6))
                .addGap(1, 1, 1)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(tfDiemly, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(tfDiemhoa, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(tfDiemtoan, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(jLabel3))
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(4, 4, 4)
                        .addComponent(btnLuu))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(btnXoa)
                            .addComponent(btnCapnhat))))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 164, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents
    private void Reset() {
        tfHoten.setText("");
        tfDiachi.setText("");
        tfDiemtoan.setText("");
        tfDiemly.setText("");
        tfDiemhoa.setText("");
    }

    private void btnLuuActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnLuuActionPerformed
        if (tfHoten.getText().equals("") || tfDiachi.getText().equals("")
                || tfDiemly.getText().equals("") || tfDiemhoa.getText().equals("")
                || tfDiemtoan.getText().equals("")) {
            JOptionPane.showMessageDialog(null, "Bạn phải nhập đầy đủ các trường!");

        } else {
            try {
                String sql = "INSERT INTO sinhvien(hoten,diachi,diemtoan,diemly,diemhoa,dtb) VALUES (?,?,?,?,?,?)";
                statement = conn.prepareStatement(sql);
                statement.setString(1, tfHoten.getText());
                statement.setString(2, tfDiachi.getText());
                statement.setString(3, tfDiemtoan.getText());
                statement.setString(4, tfDiemly.getText());
                statement.setString(5, tfDiemhoa.getText());
                Double dtb;
                dtb = (Double.parseDouble(tfDiemtoan.getText())
                        + Double.parseDouble(tfDiemly.getText())
                        + Double.parseDouble(tfDiemhoa.getText())) / 3;
                //Dung de hien thi tren Table
                //String.format("%.2f", dtb);
                statement.setDouble(6, dtb);
                int rowsInserted = statement.executeUpdate();
                System.out.print(sql);
                if (rowsInserted > 0) {
                    JOptionPane.showMessageDialog(this, "Lưu thành công");
                }
                UpdateJTable();
                Reset();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }//GEN-LAST:event_btnLuuActionPerformed

    private void formWindowOpened(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowOpened
        try {
            // TODO add your handling code here:
            conn = DBConnect.Ketnoi();
            UpdateJTable();
        } catch (Exception ex) {
            Logger.getLogger(MainForm.class.getName()).log(Level.SEVERE, null, ex);
        }
    }//GEN-LAST:event_formWindowOpened

    private void tblSinhivenMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tblSinhivenMouseClicked
        // Code by ThangTCNB
        int row = tblSinhiven.getSelectedRow();
        tfHoten.setText(tblSinhiven.getModel().getValueAt(row, 1).toString());
        tfDiachi.setText(tblSinhiven.getModel().getValueAt(row, 2).toString());
        tfDiemtoan.setText(tblSinhiven.getModel().getValueAt(row, 3).toString());
        tfDiemly.setText(tblSinhiven.getModel().getValueAt(row, 4).toString());
        tfDiemhoa.setText(tblSinhiven.getModel().getValueAt(row, 5).toString());
        /*
         String getHoten = tfHoten.getText();
         String getDiachi = tfDiachi.getText();
         String getDiemtoan = tfDiemtoan.getText();
         String getDiemly = tfDiemly.getText();
         String getDiemhoa = tfDiemhoa.getText();
         */
    }//GEN-LAST:event_tblSinhivenMouseClicked

    private void btnXoaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnXoaActionPerformed
        // TODO add your handling code here:
        int row = tblSinhiven.getSelectedRow();
        if (row == -1) {
            JOptionPane.showMessageDialog(null, "Bạn phải chọn Record cần xóa");
        } else {
            int pconfirmDelete = JOptionPane.showConfirmDialog(null, "Bạn thật sự muốn xóa?", "Xóa", JOptionPane.YES_NO_OPTION);
            if (pconfirmDelete == 0) {
                try {

                    String GetID = tblSinhiven.getModel().getValueAt(row, 0).toString();
                    String sql = "Delete from `sinhvien` where id = " + GetID;
                    statement = conn.prepareStatement(sql);
                    int rowsInserted = statement.executeUpdate();
                    if (rowsInserted > 0) {
                        JOptionPane.showMessageDialog(this, "Đã xóa thành công");
                        tfHoten.setText("");
                        tfDiachi.setText("");
                        tfDiemtoan.setText("");
                        tfDiemhoa.setText("");
                        tfDiemly.setText("");
                    }
                    UpdateJTable();
                } catch (SQLException ex) {
                    JOptionPane.showMessageDialog(null, ex);
                }
            }//end if
        }
    }//GEN-LAST:event_btnXoaActionPerformed

    private void btnCapnhatActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCapnhatActionPerformed
        // TODO add your handling code here:
        int row = tblSinhiven.getSelectedRow();
        if (row == -1) {
            JOptionPane.showMessageDialog(null, "Bạn phải chọn Record cần cập nhật");
        } else {

            try {

                String GetID = tblSinhiven.getModel().getValueAt(row, 0).toString();
                String sql = "UPDATE `sinhvien` SET"
                        + " `HoTen`=?,`DiaChi`=?,"
                        + "`DiemToan`=?,`DiemLy`=?,`DiemHoa`=?,"
                        + "`DTB`=? where id = " + GetID.toString();

                statement = conn.prepareStatement(sql);
                statement.setString(1, tfHoten.getText());
                statement.setString(2, tfDiachi.getText());
                statement.setString(3, tfDiemtoan.getText());
                statement.setString(4, tfDiemly.getText());
                statement.setString(5, tfDiemhoa.getText());
                Double dtb;
                dtb = (Double.parseDouble(tfDiemtoan.getText())
                        + Double.parseDouble(tfDiemly.getText())
                        + Double.parseDouble(tfDiemhoa.getText())) / 3;
                //Dung de hien thi tren Table
                //String.format("%.2f", dtb);
                statement.setDouble(6, dtb);
                int rowsInserted = statement.executeUpdate();
                if (rowsInserted > 0) {
                    JOptionPane.showMessageDialog(this, "Cập nhật thành công");
                    tfHoten.setText("");
                    tfDiachi.setText("");
                    tfDiemtoan.setText("");
                    tfDiemhoa.setText("");
                    tfDiemly.setText("");
                }
                UpdateJTable();
                Reset();
            } catch (Exception ex) {
                JOptionPane.showMessageDialog(null, ex);
            }
        }
    }//GEN-LAST:event_btnCapnhatActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) throws SQLException {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(MainForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(MainForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(MainForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(MainForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {

                try {
                    new MainForm().setVisible(true);
                } catch (SQLException ex) {
                    Logger.getLogger(MainForm.class.getName()).log(Level.SEVERE, null, ex);
                }

            }
        });
    }


    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnCapnhat;
    private javax.swing.JButton btnLuu;
    private javax.swing.JButton btnXoa;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JLabel lblNhapThongtin;
    private javax.swing.JTable tblSinhiven;
    private javax.swing.JTextField tfDiachi;
    private javax.swing.JTextField tfDiemhoa;
    private javax.swing.JTextField tfDiemly;
    private javax.swing.JTextField tfDiemtoan;
    private javax.swing.JTextField tfHoten;
    // End of variables declaration//GEN-END:variables
}
